//
//  ChatGroupMgr.m
//  WXIM
//
//  Created by fusuwei on 14-10-21.
//  Copyright (c) 2014年 naren. All rights reserved.
//

#import "ChatGroupMgr.h"
#import "YY_FMResultSet.h"
#import "PublicMacros.h"
#include "EPublicMacros.h"
#import "UcfgroupXMPPManger.h"
#import "Utility.h"


static BOOL initReadOnce = YES;

@implementation ChatGroupMgr

+(NSString *)getDbPathName
{
    NSString *userId = [UcfgroupXMPPManger sharedInstance].logRegWxUserObject.UserId;
    if (initReadOnce && (userId == nil)) {
        initReadOnce = NO;
        userId = [[NSUserDefaults standardUserDefaults]objectForKey:kMY_USER_ID];
    }
    NSString *fileName = [self truncateNSString:userId To:kXMPPmyDomain];
    NSString *isFilePathName = [NSString stringWithFormat:@"%@/%@",DATABASE_PATH,fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:isFilePathName]) {
        [fileManager createDirectoryAtPath:isFilePathName withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *filePathName = [NSString stringWithFormat:@"%@/%@%@",DATABASE_PATH,fileName,@"/wxChatIM.db"];
    return filePathName;
}
//将某一字符从开始位置截取到指定字符处
+ (NSString *)truncateNSString:(NSString *)srcStr To:(NSString *)toStr
{
    if (srcStr == nil) {
        return nil;
    }
    NSRange range = [srcStr rangeOfString:toStr];
    NSString *str = [srcStr substringToIndex:range.location];
    return str;
}

//检查群组、群组成员表是否存在
+(BOOL)checkChatGroupTableCreatedInDb:(YY_FMDatabase *)db
{
    BOOL worked = NO;
    NSString *createTable = @"CREATE  TABLE  IF NOT EXISTS 'GroupList' ('group_id' VARCHAR PRIMARY KEY  NOT NULL  UNIQUE , 'group_name' VARCHAR, 'group_public' VARCHAR DEFAULT '0', 'group_approval' VARCHAR DEFAULT '0', 'group_desc' VARCHAR, 'group_createTime' VARCHAR DEFAULT '0', 'group_membersMax' VARCHAR DEFAULT '0')";
    worked = [db executeUpdate:createTable];
    
    if (!worked) {
        NSLog(@"Create GroupList table resutl %d",worked);
    }
#pragma mark - 新增一个群组的备份，用于正常显示－－－
    
    createTable = @"CREATE  TABLE  IF NOT EXISTS 'GroupBackUp' ('group_id' VARCHAR PRIMARY KEY  NOT NULL  UNIQUE , 'group_name' VARCHAR)";
    worked = [db executeUpdate:createTable];
    
    if (!worked) {
        NSLog(@"Create GroupList table resutl %d",worked);
    }
    
    createTable = @"CREATE  TABLE  IF NOT EXISTS 'GroupMember' ('group_id' VARCHAR , 'member_id' VARCHAR, 'member_nickname' VARCHAR, 'member_affiliations' VARCHAR)";
    worked = [db executeUpdate:createTable];
    if (!worked) {
        NSLog(@"Create GroupMember table resutl %d",worked);
    }
    
    FMDBQuickCheck(worked);
    return worked;
}

//保存群对象到GroupbackUp表中
+(BOOL)saveChatGroupBackUpDic:(NSDictionary*)chatGroupDic
{
    if (chatGroupDic == nil) {
        return NO;
    }
    
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return NO;
    };
    [self checkChatGroupTableCreatedInDb:db];
    
    NSString *group_id = [chatGroupDic objectForKey:@"group_id"];
    
    if ([self judgeInGroupBackUpIsHaveGroupId:group_id])
    {
        BOOL ret = [self updateChatGroupBackUpDic:chatGroupDic];
        if (ret) {
            return ret;
        }
    }
    
    NSString *group_name = [chatGroupDic objectForKey:@"group_name"];
    NSString *insertStr = @"INSERT INTO  GroupBackUp ('group_id','group_name') VALUES (?,?)";
    BOOL resultFlag = [db executeUpdate:insertStr,group_id, group_name];
    
    [db close];
    return resultFlag;
}
//保存群对象到GroupList表中
+(BOOL)saveChatGroupDic:(NSDictionary*)chatGroupDic
{
    if (chatGroupDic == nil) {
        return NO;
    }
    
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return NO;
    };
    [self checkChatGroupTableCreatedInDb:db];
    
    NSString *group_id = [chatGroupDic objectForKey:@"group_id"];

    if ([self judgeInGroupListIsHaveGroupId:group_id])
    {
        BOOL ret = [self updateChatGroupDic:chatGroupDic];
        if (ret) {
            return ret;
        }
    }
    
    NSString *group_name = [chatGroupDic objectForKey:@"group_name"];
    NSString *group_public = [chatGroupDic objectForKey:@"group_public"];
    NSString *group_approval = [chatGroupDic objectForKey:@"group_approval"];
    
    NSString *group_desc = [chatGroupDic objectForKey:@"group_desc"];
    NSString *group_createTime = [chatGroupDic objectForKey:@"group_createTime"];
    NSString *group_membersMax = [chatGroupDic objectForKey:@"group_membersMax"];

    NSString *insertStr = @"INSERT INTO  GroupList ('group_id','group_name','group_public', 'group_approval', 'group_desc', 'group_createTime', 'group_membersMax') VALUES (?,?,?,?,?,?,?)";

    BOOL resultFlag = [db executeUpdate:insertStr,group_id, group_name, group_public, group_approval, group_desc, group_createTime, group_membersMax];
    
    [db close];
    return resultFlag;
}

//保存群成员对象到GroupMember表中
+(BOOL)saveChatGroupMemberDic:(NSDictionary*)chatGroupMemberDic
{
    if (chatGroupMemberDic == nil) {
        return NO;
    }
    
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return NO;
    };
    [self checkChatGroupTableCreatedInDb:db];
    
    NSString *group_id = [chatGroupMemberDic objectForKey:@"group_id"];
    NSString *member_id = [chatGroupMemberDic objectForKey:@"member_id"];
    
    if ([self judgeInGroupId:group_id ishasTheMemberId:member_id])
    {
        BOOL ret = [self updateGroupMemberDic:chatGroupMemberDic];
        if (ret) {
            return ret;
        }
    }
    
    NSString *member_nickname = [chatGroupMemberDic objectForKey:@"member_nickname"];
    NSString *member_affiliations = [chatGroupMemberDic objectForKey:@"member_affiliations"];
    
    NSString *insertStr = @"INSERT INTO GroupMember ('group_id','member_id','member_nickname', 'member_affiliations') VALUES (?,?,?,?)";
    
    BOOL resultFlag = [db executeUpdate:insertStr,group_id, member_id, member_nickname, member_affiliations];
    
    [db close];
    return resultFlag;
}
//获取某个群Id对应的群Name--GroupBackUp
+ (NSString *)fetchGroupNameInGroupBackUpByGroupId:(NSString *)groupId
{
    NSString *findName = nil;
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return @"未知";
    }
    
    NSString *queryString = @"select * from GroupBackUp where group_id=?";
    YY_FMResultSet *rs=[db executeQuery:queryString,[Utility getBareContactId:groupId]];
    while ([rs next]) {
        findName = [rs stringForColumn:@"group_name"];
    }
    
    [rs close];
    
    return findName;
}
//获取某个群Id对应的群Name
+ (NSString *)fetchGroupNameByGroupId:(NSString *)groupId
{
    NSString *findName = nil;
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return @"未知";
    }
    
    NSString *queryString = @"select * from GroupList where group_id=?";
    YY_FMResultSet *rs=[db executeQuery:queryString,[Utility getBareContactId:groupId]];
    while ([rs next]) {
        findName = [rs stringForColumn:@"group_name"];
    }
    
    [rs close];
    
    return findName;
}
//删除群表中某一个群 －－ GroupBackUp
+(BOOL)deleteGroupBackUpByGroupId:(NSString *)groupId
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return NO;
    };
    
    NSString *deleteStr = @"DELETE FROM GroupBackUp WHERE group_id = ?";
    BOOL resultFlag = [db executeUpdate:deleteStr,groupId];
    [db close];
    
    return resultFlag;
}
//删除群表中某一个群
+(BOOL)deleteGroupListByGroupId:(NSString *)groupId
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return NO;
    };
    
    NSString *deleteStr = @"DELETE FROM GroupList WHERE group_id = ?";
    BOOL resultFlag = [db executeUpdate:deleteStr,groupId];
    [db close];
    
    return resultFlag;
}

//删除群表中的所有群信息
+(BOOL)deleteAllGroupList
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return NO;
    };
    
    BOOL resultFlag = [db executeUpdate:@"DELETE FROM GroupList"];
    [db close];
    
    return resultFlag;
}

//删除群成员表中某一条记录
+(BOOL)deleteGroupMemberGroupId:(NSString *)groupId withMemberId:(NSString*)memberId
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return NO;
    };
    
    NSString *deleteStr = @"DELETE FROM GroupMember WHERE group_id = ? and member_id = ?";
    BOOL resultFlag = [db executeUpdate:deleteStr,groupId,memberId];
    [db close];
    
    return resultFlag;
}

//删除群成员表中的所有成员记录
+(BOOL)deleteAllGroupMemberByGroupId:(NSString *)groupId
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return NO;
    };
    
    NSString *deleteStr = @"DELETE FROM GroupMember WHERE group_id = ?";
    BOOL resultFlag = [db executeUpdate:deleteStr,groupId];
    [db close];
    
    return resultFlag;
}
//判断在GroupBackUp中该GroupId是否存在---GroupBackUp
+(BOOL)judgeInGroupBackUpIsHaveGroupId:(NSString*)groupId
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"isHaveTheGroupId数据库打开失败");
        return NO;
    };
    [self checkChatGroupTableCreatedInDb:db];
    
    YY_FMResultSet *rs = [db executeQuery:@"select count(*) from GroupBackUp where group_id=?",groupId];
    
    while ([rs next]) {
        int count= [rs intForColumnIndex:0];
        
        if (count!=0){
            [rs close];
            return YES;
        }else
        {
            [rs close];
            return NO;
        }
    };
    [rs close];
    return NO;
}
//判断在GroupList中该GroupId是否存在
+(BOOL)judgeInGroupListIsHaveGroupId:(NSString*)groupId
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"isHaveTheGroupId数据库打开失败");
        return NO;
    };
    [self checkChatGroupTableCreatedInDb:db];
    
    YY_FMResultSet *rs = [db executeQuery:@"select count(*) from GroupList where group_id=?",groupId];
    
    while ([rs next]) {
        int count= [rs intForColumnIndex:0];
        
        if (count!=0){
            [rs close];
            return YES;
        }else
        {
            [rs close];
            return NO;
        }
    };
    [rs close];
    return NO;
}

//判断在GroupMember中该GroupId和memberId是否同时存在一条记录
+(BOOL)judgeInGroupId:(NSString*)groupId ishasTheMemberId:(NSString*)memberId
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return YES;
    };
    [self checkChatGroupTableCreatedInDb:db];
    
    YY_FMResultSet *rs = [db executeQuery:@"select count(*) from GroupMember where group_id=? and member_id=?",groupId,memberId];
  
    while ([rs next])
    {
        int count= [rs intForColumnIndex:0];
        
        if (count!=0){
            [rs close];
            return YES;
        }else
        {
            [rs close];
            return NO;
        }
    };
    [rs close];
    return NO;
}
//更新群组GroupBackUp
+(BOOL)updateChatGroupBackUpDic:(NSDictionary*)chatGroupDic
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return NO;
    };
    
    [ChatGroupMgr checkChatGroupTableCreatedInDb:db];
    
    NSString *group_id = [chatGroupDic objectForKey:@"group_id"];
    NSString *group_name = [chatGroupDic objectForKey:@"group_name"];
    BOOL worked = [db executeUpdate:@"UPDATE GroupBackUp SET group_name=? where group_id=?",
                   group_name, group_id];
    
    [db close];
    return worked;
}
//更新群组GroupList
+(BOOL)updateChatGroupDic:(NSDictionary*)chatGroupDic
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return NO;
    };
    
    [ChatGroupMgr checkChatGroupTableCreatedInDb:db];
    
    NSString *group_id = [chatGroupDic objectForKey:@"group_id"];
    NSString *group_name = [chatGroupDic objectForKey:@"group_name"];
    NSString *group_public = [chatGroupDic objectForKey:@"group_public"];
    NSString *group_approval = [chatGroupDic objectForKey:@"group_approval"];

    NSString *group_desc = [chatGroupDic objectForKey:@"group_desc"];
    NSString *group_createTime = [chatGroupDic objectForKey:@"group_createTime"];
    NSString *group_membersMax = [chatGroupDic objectForKey:@"group_membersMax"];
    
    BOOL worked = [db executeUpdate:@"UPDATE GroupList SET group_name=?, group_public=?, group_approval=?, group_desc=?, group_createTime=?, group_membersMax=? where group_id=?",
                   group_name, group_public,group_approval, group_desc, group_createTime, group_membersMax, group_id];
    
    [db close];
    
    return worked;
}

//更新群组成员GroupMember
+(BOOL)updateGroupMemberDic:(NSDictionary*)chatGroupMemberDic
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return NO;
    };
    
    [ChatGroupMgr checkChatGroupTableCreatedInDb:db];
    
    NSString *group_id = [chatGroupMemberDic objectForKey:@"group_id"];
    NSString *member_id = [chatGroupMemberDic objectForKey:@"member_id"];
    NSString *member_nickname = [chatGroupMemberDic objectForKey:@"member_nickname"];
    NSString *member_affiliations = [chatGroupMemberDic objectForKey:@"member_affiliations"];
    
    BOOL worked = [db executeUpdate:@"UPDATE GroupMember SET member_nickname=?, member_affiliations=? where group_id=? and member_id=?",
                   member_nickname, member_affiliations, group_id, member_id];
    
    [db close];
    return worked;
}


//读取所有群组的列表
+(NSMutableArray*)readAllGroupListArray
{
    NSMutableArray *resultArr=[[NSMutableArray alloc] init];
    
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return resultArr;
    };
    
    [ChatGroupMgr checkChatGroupTableCreatedInDb:db];
    
    YY_FMResultSet *rs = [db executeQuery:@"select * from GroupList"]; //where roomjid=?",[NSNumber numberWithInt:255]
    
    while ([rs next]) {
        ChatGroup *user=[[ChatGroup alloc] init];
        user.group_id=[rs stringForColumn:@"group_id"];
        user.group_name=[rs stringForColumn:@"group_name"];
        user.group_public=[rs stringForColumn:@"group_public"];
        user.group_approval=[rs stringForColumn:@"group_approval"];
        user.group_desc = [rs stringForColumn:@"group_desc"];
        user.group_createTime=[rs stringForColumn:@"group_createTime"];
        user.group_membersMax=[rs stringForColumn:@"group_membersMax"];
        
        user.group_HeadPicUrl = [NSString stringWithFormat:@"%@%@%@",[[UcfgroupXMPPManger sharedInstance] getFileServer],@"/file_download.yaws/files/small/",user.group_id];
        [resultArr addObject:user];
    }
    [rs close];
    [db close];
    return resultArr;
}

//读取某一群组的信息
+(ChatGroup *)readChatGroupMsgbyGroupId:(NSString*)groupId
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return nil;
    };
    
    [ChatGroupMgr checkChatGroupTableCreatedInDb:db];
    
    YY_FMResultSet *rs = [db executeQuery:@"select * from GroupList where group_id= ?",groupId];
    
    NSInteger findcount = -1;
    ChatGroup *user= nil;
    while ([rs next]) {
        user= [[ChatGroup alloc] init];
        
        findcount= [rs intForColumnIndex:0];
        user.group_id=[rs stringForColumn:@"group_id"];
        user.group_name=[rs stringForColumn:@"group_name"];
        user.group_public=[rs stringForColumn:@"group_public"];
        user.group_approval=[rs stringForColumn:@"group_approval"];
        user.group_desc = [rs stringForColumn:@"group_desc"];
        user.group_createTime=[rs stringForColumn:@"group_createTime"];
        user.group_membersMax=[rs stringForColumn:@"group_membersMax"];
        user.group_HeadPicUrl = [NSString stringWithFormat:@"%@%@%@",[[UcfgroupXMPPManger sharedInstance] getFileServer],@"/file_download.yaws/files/small/",user.group_id];
    }
    [rs close];
    [db close];
    
    if (findcount != -1) {
        return user;
    }
    return nil;
}

//读取某一群组的所有成员
+(NSMutableArray*)readGroupMemberArrayByGroupId:(NSString*)groupId
{
    NSMutableArray *resultArr=[[NSMutableArray alloc] init];
    
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return resultArr;
    };
    [ChatGroupMgr checkChatGroupTableCreatedInDb:db];
    
    YY_FMResultSet *rs=[db executeQuery:@"select * from GroupMember where group_id=?",groupId];
    
    while ([rs next]) {
        ChatGroupMember *user = [[ChatGroupMember alloc] init];
        user.member_id=[rs stringForColumn:@"member_id"];
        user.member_nickname=[rs stringForColumn:@"member_nickname"];
        user.member_affiliations=[rs stringForColumn:@"member_affiliations"];
        [resultArr addObject:user];
    }
    [rs close];
    [db close];
    return resultArr;
}

//读取某一群组的某一个成员信息
+(ChatGroupMember*)readGroupMemberByGroupId:(NSString*)groupId withMemberId:(NSString*)memberId
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return nil;
    };
    [ChatGroupMgr checkChatGroupTableCreatedInDb:db];
    
    YY_FMResultSet *rs=[db executeQuery:@"select * from GroupMember where group_id=? and member_id=?",groupId,memberId];
    
    NSInteger findcount = -1;
    ChatGroupMember *user = [[ChatGroupMember alloc] init];
    while ([rs next]) {
        findcount= [rs intForColumnIndex:0];
        user.member_id=[rs stringForColumn:@"member_id"];
        user.member_nickname=[rs stringForColumn:@"member_nickname"];
        user.member_affiliations=[rs stringForColumn:@"member_affiliations"];
    }
    [rs close];
    [db close];
    
    if (findcount != -1) {
        return user;
    }
    return nil;
}


@end
